package com.czk.netty.netty.tcp.protocaltcp.practice.client;

import com.czk.netty.netty.tcp.protocaltcp.practice.protocol.TransferProtocol;
import com.czk.netty.netty.tcp.protocaltcp.protocol.MessageProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/8 11:22
 */
public class ClientHandler extends SimpleChannelInboundHandler<TransferProtocol> {
    private int count = 0;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        // 发送消息
        for (int i = 0; i < 10; i++) {
            String str = "今天杜兰特狂砍31分";
            byte[] content = str.getBytes(Charset.forName("UTF-8"));
            int len = str.getBytes(Charset.forName("UTF-8")).length;
            // 封装对象
            TransferProtocol transferProtocol = new TransferProtocol();
            transferProtocol.setContent(content);
            transferProtocol.setLength(len);
            ctx.writeAndFlush(transferProtocol);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TransferProtocol transferProtocol) throws Exception {
        // 读取数据
        // 接收消息
        byte[] content = transferProtocol.getContent();
        int len = transferProtocol.getLength();
        System.out.println("客户端接收的消息长度=" + len);
        System.out.println("客户端接收的内容=" + new String(content, StandardCharsets.UTF_8));
        System.out.println("接收的次数=" + (++this.count));
    }
}
